<template>
  <div class="container">
    <div class="apply-container">
      <div class="apply-container-head"></div>
      <div class="apply-container-body">
        <div class="apply-container-body-title">
          <div class="apply-container-body-title-font">用车申请</div>
          <div class="apply-container-body-title-return">
            <el-button size="small" @click="goBackPage">返回</el-button>
          </div>
        </div>
        <el-divider class="apply-container-body-title-line"></el-divider>
        <div class="apply-container-body-content">
          <el-form :model="AutoOrder" label-width="100px" ref="AutoOrder" label-position="LabelPosition"
            :rules="AutoOrderRules" style="width: 100%;">
            <el-form-item label="用车部门:" prop="SelectUserDepartment" style="width: 38%;">
              <el-select v-model="AutoOrder.SelectUserDepartment" placeholder="请选择用车部门" clearable>
                <el-option label="销售部" value="销售部"></el-option>
                <el-option label="财务部" value="财务部"></el-option>
                <el-option label="市场部" value="市场部"></el-option>
                <el-option label="技术部" value="技术部"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="姓名:" prop="InputUserName" style="width: 40%;">
              <el-input v-model="AutoOrder.InputUserName" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="工号:" prop="InputUserId" style="width: 40%;">
              <el-input v-model="AutoOrder.InputUserId" placeholder="请输入工号" clearable></el-input>
            </el-form-item>
            <el-form-item label="申请人电话:" prop="InputUserPhone" style="width: 40%;">
              <el-input v-model="AutoOrder.InputUserPhone" placeholder="请输入申请人电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="车型:" prop="SelectAutoType" style="width: 38%;">
              <el-select v-model="AutoOrder.SelectAutoType" placeholder="请选择车型" clearable>
                <el-option label="商务车" value="商务车"></el-option>
                <el-option label="客车" value="客车"></el-option>
                <el-option label="货车" value="货车"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="成员数:" prop="InputPassengerNum" style="width: 40%;">
              <el-input v-model="AutoOrder.InputPassengerNum" placeholder="请输入成员数" clearable></el-input>
            </el-form-item>
            <el-form-item label="用车时间:" prop="AutoStartTime" style="width: 38%;">
              <el-date-picker v-model="AutoOrder.AutoStartTime" type="datetime" value-format="yyyy-MM-dd-HH-mm"
                placeholder="请选择日期时间" clearable></el-date-picker>
            </el-form-item>
            <el-form-item label="截止时间:" prop="AutoArriveTime" style="width: 38%;">
              <el-date-picker v-model="AutoOrder.AutoArriveTime" type="datetime" value-format="yyyy-MM-dd-HH-mm"
                placeholder="请选择日期时间" clearable></el-date-picker>
            </el-form-item>
            <el-form-item label="目的地:" prop="InputUserDestination" style="width: 50%;">
              <el-input v-model="AutoOrder.InputUserDestination" placeholder="请输入目的地" clearable></el-input>
            </el-form-item>
            <el-form-item label="用车事由:" prop="InputAutoUseReason" style="width: 50%;">
              <el-input v-model="AutoOrder.InputAutoUseReason" type="textarea" placeholder="请输入内容" maxlength="100"
                show-word-limit></el-input>
            </el-form-item>
            <div class="apply-container-body-content-submit">
              <el-button type="primary" @click="Submit('AutoOrder')">提交</el-button>
            </div>
          </el-form>
        </div>
      </div>
      <div class="apply-container-footer"></div>
    </div>
  </div>
</template>

<script>
import { addAutoOrder } from '@/api/application.js'
import { queryDepartmentUserId } from '@/api/todo.js';
import { getAutoOrderId } from '@/api/application.js'
import { insertTodo } from '@/api/todo.js';
import { getUserInfoById } from '@/api/user.js';
export default {
  name: 'AutoApplicationView',
  data() {
    return {
      LabelPosition: 'right',
      AutoOrder: {
        SelectUserDepartment: null,
        InputUserName: null,
        InputUserId: null,
        InputUserPhone: null,
        SelectAutoType: null,
        InputPassengerNum: null,
        AutoStartTime: null,
        AutoArriveTime: null,
        InputUserDestination: null,
        InputAutoUseReason: null,
        SubmitTime: null,
      },
      AutoOrderRules: {
        SelectUserDepartment: [{ required: true, message: '请选择用车部门', trigger: 'change' },],
        InputUserName: [{ required: true, message: '请输入姓名', trigger: 'blur' },],
        InputUserId: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 8, max: 8, message: '工号长度为 8', trigger: 'blur' }
        ],
        InputUserPhone: [
          { required: true, message: '请输入申请人电话', trigger: 'blur' },
          { min: 11, max: 11, message: '电话长度为 11', trigger: 'blur' }
        ],
        SelectAutoType: [{ required: true, message: '请选择车型', trigger: 'change' },],
        InputPassengerNum: [{ required: true, message: '请输入成员数', trigger: 'blur' },],
        AutoStartTime: [{ type: 'string', required: true, message: '请输入时间', trigger: 'blur' },],
        AutoArriveTime: [{ type: 'string', required: true, message: '请输入时间', trigger: 'blur' },],
        InputUserDestination: [
          { required: true, message: '请输入目的地', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        InputAutoUseReason: [{ required: true, message: '请输入用车事由', trigger: 'blur' },],
      },
      SubmitAutoOrder: {
        userName: null,
        userId: null,
        userPhone: null,
        autoType: null,
        passengerNum: null,
        autoStartTime: null,
        autoArriveTime: null,
        userDepartment: null,
        userDestination: null,
        autoUseReason: null,
        submitTime: null,
        autoOrderStatus: null,
        autoOrderProgress: null,
      },
      SubmitTodo: {
        userId: null,
        todoTime: null,
        todoType: null,
        orderId: null,
        todoStatus: null,
      },

      DepartmentAdminId: null,
      NextUserRole: "部门管理员",
      AutoOrderId: null,
      SubmitCode: [],
    }
  },

  methods: {
    UpdateCurrentTime() {
      const currentDateTime = new Date();
      const dateOptions = { year: 'numeric', month: '2-digit', day: '2-digit' };
      const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
      const formattedDate = currentDateTime.toLocaleDateString(undefined, dateOptions);
      const formattedTime = currentDateTime.toLocaleTimeString(undefined, timeOptions);
      this.AutoOrder.SubmitTime = `${formattedDate} ${formattedTime}`;
    },
    AddAutoOrder() {
      return new Promise((resolve, reject) => {
        this.SubmitAutoOrder.userDepartment = this.AutoOrder.SelectUserDepartment;
        this.SubmitAutoOrder.userName = this.AutoOrder.InputUserName;
        this.SubmitAutoOrder.userId = this.AutoOrder.InputUserId;
        this.SubmitAutoOrder.userPhone = this.AutoOrder.InputUserPhone;
        this.SubmitAutoOrder.autoType = this.AutoOrder.SelectAutoType;
        this.SubmitAutoOrder.passengerNum = this.AutoOrder.InputPassengerNum;
        this.SubmitAutoOrder.autoStartTime = this.AutoOrder.AutoStartTime;
        this.SubmitAutoOrder.autoArriveTime = this.AutoOrder.AutoArriveTime;
        this.SubmitAutoOrder.userDestination = this.AutoOrder.InputUserDestination;
        this.SubmitAutoOrder.autoUseReason = this.AutoOrder.InputAutoUseReason;
        this.SubmitAutoOrder.submitTime = this.AutoOrder.SubmitTime;
        this.SubmitAutoOrder.autoOrderStatus = "流转中";
        this.SubmitAutoOrder.autoOrderProgress = 1;
        addAutoOrder(this.SubmitAutoOrder)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    QueryDepartmentUserId() {
      return new Promise((resolve, reject) => {
        queryDepartmentUserId(this.NextUserRole, this.AutoOrder.SelectUserDepartment)
          .then(res => {
            const temp = res.data.data;
            const result = Object.values(temp);
            this.DepartmentAdminId = result[0];
            resolve(); // 表示异步操作成功
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    GetAutoOrderId() {
      return new Promise((resolve, reject) => {
        getAutoOrderId(this.SubmitAutoOrder.submitTime)
          .then(res => {
            const temp = res.data.data;
            const result = Object.values(temp);
            this.AutoOrderId = result[0];
            resolve(); // 表示异步操作成功
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    AddTodo() {
      return new Promise((resolve, reject) => {
        this.SubmitTodo.userId = this.DepartmentAdminId;
        this.SubmitTodo.todoTime = this.AutoOrder.SubmitTime;
        this.SubmitTodo.todoType = "用车申请部门审批";
        this.SubmitTodo.orderId = this.AutoOrderId; // 待工单提交到数据库后从后端获取
        this.SubmitTodo.todoStatus = '未完成';
        insertTodo(this.SubmitTodo)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    //检错，可复用
    JudgeSubmitCode(data) {
      const allZeros = data.every(code => code === '0');
      return allZeros;
    },
    showMessage(message, type) {
      this.$message({
        message: message,
        duration: 2000,
        showClose: true,
        type: type,
      });
    },
    goBackPage() {
      this.$router.go(-1)
    },
    JudgeSuccess(data) {
      if (this.JudgeSubmitCode(data)) {
        this.showMessage('新建申请成功!', 'success');
        this.goBackPage();
      } else
        this.showMessage('新建申请失败!', 'error');
    },
    Submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('此操作将提交该用车申请, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.UpdateCurrentTime();
            this.AddAutoOrder()
              .then(() => this.QueryDepartmentUserId())
              .then(() => this.GetAutoOrderId())
              .then(() => this.AddTodo())
              .then(() => this.JudgeSuccess(this.SubmitCode))
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }
        else {
          return false;
        }
      })
    },
    InitData() {
      return new Promise((resolve, reject) => {
        try {
          getUserInfoById(localStorage.getItem("userId")).then(res => {
            const data = res.data.data;
            this.AutoOrder.InputUserName = data[0].userName;
            this.AutoOrder.InputUserId = data[0].userId;
            this.AutoOrder.InputUserPhone = data[0].userPhone;
            this.AutoOrder.SelectUserDepartment = data[0].userDepartment;
          })
          resolve(); // 表示异步操作成功
        } catch (error) {
          console.log(error);
          reject(error); // 处理异步错误
        }
      });
    },
  },
  created() {
    this.InitData();
  },
}
</script>

<style scoped>
.container {
  /* height: 100%; */
  width: 95%;
  margin: 0 auto;
  margin-top: 1%;
  background-color: #ffffff;
}

.apply-container {
  width: 90%;
  height: 100%;
  margin: 0 auto;
  /* background-color: #f2f2f2; */

}

.apply-container-head {
  width: 95%;
  height: 30px;
  margin: 0 auto;
}

.apply-container-body {
  width: 95%;
  height: 92%;
  margin: 0 auto;
  background-color: #ffffff;

}

.apply-container-body-title {
  width: 98%;
  height: 5%;
  margin: 0 auto;
  display: flex;
}

.apply-container-body-title-return {
  width: 100%;
  padding-top: 5px;
  display: flex;
  justify-content: flex-end;
}

.apply-container-body-title-line {
  height: 1px;
  width: 98%;
  margin: 5px auto;
}

.apply-container-body-title-font {
  width: 100%;
  height: 99%;
  font-size: 18px;
  font-weight: bold;
  text-align: left;
  padding-top: 10px;
}

.apply-container-body-content {
  width: 85%;
  height: 100%;
  margin: 20px auto;
  display: flex;

}

.apply-container-body-content-submit {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.apply-container-footer {
  width: 95%;
  height: 10px;
  margin: 0 auto;
}
</style>